package com.dongdongshop.config;


import com.dongdongshop.api.UserServiceApi;
import com.dongdongshop.data.Result;
import com.dongdongshop.dto.UserDTO;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class LoginRealm extends AuthorizingRealm {

    @Autowired
    private UserServiceApi userServiceApi;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String username = usernamePasswordToken.getUsername();
        //效验密码
        Result<UserDTO> userByName = userServiceApi.getUserByName(username);
        UserDTO userDTO = userByName.getData();
        if (userDTO == null) {
            return null;
        }
        /*账号相同去效验密码*/
        return new SimpleAuthenticationInfo(userDTO, userDTO.getPassword(), ByteSource.Util.bytes(userDTO.getSalt()), userDTO.getUsername());
    }
}
